/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.vo.HljgDspVo;
import me.zhengjie.business.domain.vo.KC04;
import me.zhengjie.business.repository.ZhsqRepository;
import me.zhengjie.business.service.Kc04Service;
import me.zhengjie.business.service.dto.ZhsqDto;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.DateTimeUtil;
import me.zhengjie.utils.DefaultUtil;
import me.zhengjie.utils.GetSndj;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-05-25
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class Kc04ServiceImpl implements Kc04Service {


    private final ZhsqRepository zhsqRepository;
    @PersistenceContext
    private EntityManager em;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public KC04 findKc04(String grbh) {
        int year = DateTimeUtil.getCurrentYear();
        KC04 kc04 = new KC04();
        String sql = "select AKC318 from kc04 where aac001 = :grbh and aae001 = :year  ";
        Query query = em.createNativeQuery(sql);
        query.setParameter("grbh", grbh);
        query.setParameter("year", year);
        List result = query.getResultList();
        if(result.size() == 0) {
            kc04.setAac001("");
            kc04.setAkc318("");

            return kc04;
        } else {
            log.info("result {} ", result);
            for (Object obj : result) {

                kc04.setAac001(grbh);
                kc04.setAkc318(obj);
            }

            return kc04;
        }
    }

    @Override
    public ZhsqDto queryBySfz(String sfz) {
        String sql = "select r.*" +
                "  from (select view_person.AAC001, " +
                "               view_person.AAC002, " +
                "               view_person.AAC003, " +
                "               view_person.CARDNO, " +
                "               view_person.AAC031, " +
                "               view_person.AAC008, " +
                "               view_person.AAB034_CODE, " +
                "               to_char(kc20.AAE030, 'yyyy-mm-dd hh24:mi:ss') AAE030, " +
                "               to_char(kc20.AAE031, 'yyyy-mm-dd hh24:mi:ss') AAE031, " +
                "               kc55.AKC552, " +
                "               kc55.AKC553, " +
                "               kc55.AKC511 " +
                "          from kc20, kc55, view_person " +
                "         where kc20.aae073 = kc55.aae073 " +
                "           and kc55.aac002 = view_person.aac002 " +
                "           and kc55.aac002 = :sfz " +
                "         order by kc20.aae030 desc) r " +
                " where rownum = 1 ";
        Query query = em.createNativeQuery(sql);
        query.setParameter("sfz", sfz);
        List result = query.getResultList();
        ZhsqDto zhsqDto = new ZhsqDto();
        for (Object obj : result) {
            Object[] arr = (Object[]) obj;

            int index17 = Integer.parseInt(((String)arr[1]).substring(16, 17));
            String xb = (index17&1) == 1 ? "男" : "女";

            Date dykkrq = DateTimeUtil.parse((String)arr[7], DateTimeUtil.DEFAULT_DATETIME_FORMAT);
            Date dyjsrq = DateTimeUtil.parse((String)arr[8], DateTimeUtil.DEFAULT_DATETIME_FORMAT);

            int diffMonths = DateTimeUtil.diffMonths(dyjsrq, dykkrq);

            int csnd = Integer.parseInt(((String)arr[1]).substring(6, 10));
            int csrq = Integer.parseInt(((String)arr[1]).substring(10, 14));
            // const csnd = 1937
            // const csrq = 1208
            String currentDate = DateTimeUtil.getDateTime("yyyyMMdd");
            int currentNd = Integer.parseInt(currentDate.substring(0,4));
            int currentRq = Integer.parseInt(currentDate.substring(4,7));
            // 当前日期 >= 出生日期的，年龄+1
            int nl = currentRq >= csrq ? currentNd - csnd : currentNd - csnd - 1;


            Map<String, String> snMap = GetSndj.analyse(((BigDecimal)arr[11]).intValue(), nl);

            String sndj = snMap.get(GetSndj.SNDJ);

            zhsqDto.setBisZhsqId(0l);
            zhsqDto.setBisZhsqLxdh("");
            zhsqDto.setBisZhsqGx("");
            zhsqDto.setBisZhsqSndj(sndj);
            zhsqDto.setBisZhsqXsdyq(diffMonths+"个月");
            zhsqDto.setBisZhsqSnryXb(xb);

            zhsqDto.setBisZhsqGrbh((String)arr[0]);
            zhsqDto.setBisZhsqSnrySfz((String)arr[1]);
            zhsqDto.setBisZhsqSnryXm((String)arr[2]);
            zhsqDto.setBisZhsqYbkh((String)arr[3]);
            zhsqDto.setBisZhsqCbzt((String)arr[4]);
            zhsqDto.setBisZhsqCblx((String)arr[5]);
            zhsqDto.setBisZhsqSnryYbssqx((String)arr[6]);
            zhsqDto.setBisZhsqDykkrq(dykkrq);
            zhsqDto.setBisZhsqDyjsrq(dyjsrq);
            zhsqDto.setBisZhsqJhrxm((String)arr[9]);
            zhsqDto.setBisZhsqJhrdh((String)arr[10]);
        }
        return zhsqDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void stopZhsq(String sfz, String zzrq, Long zhid, String zzyy) {
        log.info("[Kc04ServiceImpl - stopZhsq]--------------- 机构执行终止待遇 - 开始");
        log.info("[Kc04ServiceImpl - stopZhsq]--------------- 机构执行终止待遇 - sfz:{}，zzrq:{}，zhid:{}，zzyy:{}", sfz, zzrq, zhid, zzyy);
        log.info("[Kc04ServiceImpl - stopZhsq]--------------- 机构执行终止待遇 - 执行PRC_MAKE_2901_STOP_HISTORY");

        StoredProcedureQuery storedProcedureQuery = this.em.createNamedStoredProcedureQuery("stopZhsq");

        storedProcedureQuery.setParameter("IR_SFZ", sfz);
        storedProcedureQuery.setParameter("IR_ZZYY", zzyy);
        storedProcedureQuery.setParameter("IR_ZZRQ", zzrq.replaceAll("-", ""));

        storedProcedureQuery.execute();
        int code = (int) storedProcedureQuery.getOutputParameterValue("OR_APPCODE");
        String msg = (String) storedProcedureQuery.getOutputParameterValue("OR_MESSAGE");

        log.info("[Kc04ServiceImpl - stopZhsq]--------------- 机构执行终止待遇 - 结束 :code:{}，msg:{}", code, msg);
        if(code == -1) {
            throw new BadRequestException(msg);
        }
    }
}